package com.syni.mdd.sjb.common.component.utils.redis.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @className RedisTemplateUtils
 * @description TOO
 * @Author cfx
 * @DATE 2019/5/5 18:19
 * @VERSION 1.0
 **/
@Component
public class RedisDistributedLockUtils {

    public static RedissonClient redissonClient;

    @Autowired
    public void setRedissonClient(RedissonClient redissonClient){
        RedisDistributedLockUtils.redissonClient = redissonClient;
    }


    /**
     * 无限拿锁
     * 锁的默认时间是30s,10s以后如果业务没执行完，自动对锁进行续命
     * @param lockKey
     * @return
     */
    public static boolean lock(String lockKey){
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock.isLocked();
    }

    /**
     * 无限拿锁
     * 超过time时间自动解锁
     * @param lockKey
     * @return
     */
    public static boolean lock(String lockKey,TimeUnit timeUnit,Long time){
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(time,timeUnit);
        return lock.isLocked();
    }

    /**
     * 尝试获取锁，超过一定时间返回
     * 超过lockTime时间自动解锁
     * @param lockKey
     * @return
     */
    public static boolean tryLock(String lockKey,TimeUnit timeUnit,Long getTime,Long lockTime){
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean lockResult = lock.tryLock(getTime,lockTime,timeUnit);
            return lockResult;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 尝试获取锁，超过一定时间返回
     * 锁的默认时间是30s,10s以后如果业务没执行完，自动对锁进行续命
     * 推荐使用
     * @param lockKey
     * @return
     */
    public static boolean tryLock(String lockKey,TimeUnit timeUnit,Long time){
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean lockResult = lock.tryLock(time,timeUnit);
            return lockResult;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }



    /**
     * 解锁
     * @param lockKey
     */
    public static void unlock(String lockKey){
        RLock lock = redissonClient.getLock(lockKey);
        if(lock.isHeldByCurrentThread()){
            lock.unlock();
        }
    }

}
